package com.telit.dispose.service.resourceManagement.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.telit.common.entity.PageData;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.GeoUtils;
import com.telit.dispose.dao.dispose.PlatMetaFieldMapper;
import com.telit.dispose.dao.dispose.PlatMetaTableMapper;
import com.telit.dispose.dao.resourceManagement.FireResourceCategoryDao;
import com.telit.dispose.dto.FireResourceCategoryDTO;
import com.telit.dispose.dto.PlatMetaTableEntityDTO;
import com.telit.dispose.entity.FireResourceCategory;
import com.telit.dispose.entity.dispose.PlatMetaTableEntity;
import com.telit.dispose.enums.ResourceEnums;
import com.telit.dispose.model.QryDeviceListRequest;
import com.telit.dispose.model.QryDeviceModel;
import com.telit.dispose.model.QryResourceListRequest;
import com.telit.dispose.model.QryResourceModel;
import com.telit.dispose.resource.QryCatListRequest;
import com.telit.dispose.service.dispose.PlatMetaTableService;
import com.telit.dispose.service.resourceManagement.FireResourceService;
import com.telit.dispose.vo.dispose.PlatTableVO;
import com.telit.dispose.vo.resourceManagement.FireSituationVO;
import com.telit.dispose.vo.resourceManagement.ResourceCategoryVO;
import com.telit.dispose.vo.resourceManagement.ResourceSimpVO;
import com.telit.dispose.vo.resourceManagement.TopFloorDownDistrictCodeVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 防火资源
 *
 * @author yuezhuang
 * @date 2022-08-29
 */
@Slf4j
@Service
public class FireResourceServiceImpl implements FireResourceService {

    @Autowired
    private FireResourceCategoryDao fireResourceCategoryDao;

    @Autowired
    private PlatMetaFieldMapper platMetaFieldMapper;

    @Autowired
    private PlatMetaTableMapper platMetaTableMapper;

    @Autowired
    private PlatMetaTableService platMetaTableService;

    //视频监控表名称
    private final String TABLE_NAME_SHIPINJIANKONG = "comm_camera_info";


    @Override
    public void addResource(FireResourceCategory fireResourceCategory) {
        if (fireResourceCategoryDao.insert(fireResourceCategory) <= 0) {
            throw new ForestBaseException("新增防火资源");
        }
    }

    @Override
    public void updateResource(FireResourceCategory fireResourceCategory) {
        if (fireResourceCategory.getId() == null) {
            throw new ForestBaseException("id不能为空");
        }
        fireResourceCategoryDao.updateResource(fireResourceCategory.getImg(), fireResourceCategory.getId());
    }

    /**
     * 查询分类树
     *
     * @return FireResourceCategoryDTO
     */
    @Override
    public List<FireResourceCategoryDTO> qryCatTree() {
        QueryWrapper<FireResourceCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", false);
        wrapper.orderByAsc("id");
        List<FireResourceCategory> categoryList = fireResourceCategoryDao.selectList(wrapper);

        //一级
        List<FireResourceCategoryDTO> firstLevel = categoryList.stream().filter(
                fireResourceCategory -> fireResourceCategory.getParentId().intValue() == 0)
                .map(fireResourceCategory -> Convert.convert(FireResourceCategoryDTO.class, fireResourceCategory))
                //img字段为null时转换成""
                .peek(fireResourceCategoryDTO -> {
                    if (fireResourceCategoryDTO.getImg() == null) {
                        fireResourceCategoryDTO.setImg("");
                    }
                })
                .sorted(Comparator.comparingInt(FireResourceCategoryDTO::getSortNum))
                .collect(Collectors.toList());
        //二级
        firstLevel = firstLevel.stream().map(fireResourceCategoryDTO -> {
            List<FireResourceCategoryDTO> secondLevel = categoryList.stream().filter(fireResourceCategory ->
                    fireResourceCategory.getParentId().compareTo(fireResourceCategoryDTO.getId()) == 0)
                    .map(fireResourceCategory -> Convert.convert(FireResourceCategoryDTO.class, fireResourceCategory))
                    .peek(secondDTO -> {
                        if (secondDTO.getImg() == null) {
                            secondDTO.setImg("");
                        }
                    })
                    .sorted((o1, o2) -> {
                        if (o1.getSortNum() > o2.getSortNum()) {
                            return 1;
                        } else if (o1.getSortNum() == o2.getSortNum()) {
                            return o1.getId().compareTo(o2.getId());
                        } else {
                            return -1;
                        }
                    })
                    .collect(Collectors.toList());
            fireResourceCategoryDTO.setChildList(secondLevel);
            return fireResourceCategoryDTO;
        }).collect(Collectors.toList());

        return firstLevel;
    }

    /**
     * 查询分类列表
     * <p>
     * 仅搜索资源类型（二级分类）
     * </p>
     *
     * @param qryCatListRequest QryCatListRequest
     *
     * @return FireResourceCategoryDTO
     */
    @Override
    public List<FireResourceCategoryDTO> qryCatList(QryCatListRequest qryCatListRequest) {
        QueryWrapper<FireResourceCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", false);
        wrapper.orderByAsc("id");
        List<FireResourceCategory> categoryList = fireResourceCategoryDao.selectList(wrapper);

        //一级
        List<FireResourceCategoryDTO> firstLevel = categoryList.stream().filter(
                fireResourceCategory -> fireResourceCategory.getParentId().intValue() == 0)
                .map(fireResourceCategory -> Convert.convert(FireResourceCategoryDTO.class, fireResourceCategory))
                //img字段为null时转换成""
                .peek(fireResourceCategoryDTO -> {
                    if (fireResourceCategoryDTO.getImg() == null) {
                        fireResourceCategoryDTO.setImg("");
                    }
                })
                .sorted(Comparator.comparingInt(FireResourceCategoryDTO::getSortNum))
                .collect(Collectors.toList());
        //二级
        firstLevel = firstLevel.stream()
                .map(fireResourceCategoryDTO -> {
                    List<FireResourceCategoryDTO> secondLevel = categoryList.stream()
                            .filter(fireResourceCategory ->
                                    fireResourceCategory.getParentId().compareTo(fireResourceCategoryDTO.getId()) == 0)
                            //模糊关键字查询
                            .filter(fireResourceCategory -> {
                                if (StringUtils.isNotBlank(qryCatListRequest.getKeyWords())) {
                                    return fireResourceCategory.getCatName().contains(qryCatListRequest.getKeyWords());
                                }
                                return true;
                            })
                            //父类id查询
                            .filter(fireResourceCategory -> {
                                if (qryCatListRequest.getParentId() != null) {
                                    return fireResourceCategory.getParentId().compareTo(qryCatListRequest.getParentId())
                                            == 0;
                                }
                                return true;
                            })
                            .map(fireResourceCategory -> Convert.convert(FireResourceCategoryDTO.class,
                                    fireResourceCategory))
                            //img字段为null时转换成""
                            .peek(secondDTO -> {
                                if (secondDTO.getImg() == null) {
                                    secondDTO.setImg("");
                                }
                            })
                            .sorted((o1, o2) -> {
                                if (o1.getSortNum() > o2.getSortNum()) {
                                    return 1;
                                } else if (o1.getSortNum() == o2.getSortNum()) {
                                    return o1.getId().compareTo(o2.getId());
                                } else {
                                    return -1;
                                }
                            })
                            .collect(Collectors.toList());
                    fireResourceCategoryDTO.setChildList(secondLevel);
                    return fireResourceCategoryDTO;
                })
                .collect(Collectors.toList());

        return firstLevel;
    }

    @Override
    public List<ResourceCategoryVO> topFloorList(Long parentId) {
        List<ResourceCategoryVO> result = fireResourceCategoryDao.selectListByParentId(parentId);
        return result;
    }

    //包含子类以及子类数量
    @Override
    public List<ResourceCategoryVO> topFloorDownChildrenList(Long parentId, String longitude, String latitude,
                                                             String radius, String districtCode) {
        if (StringUtils.isNotBlank(districtCode)) {
            districtCode = districtCode + "%";
        }
        //查询所有的资源分类
        List<ResourceCategoryVO> result = fireResourceCategoryDao.selectListByParentId(parentId);
        for (ResourceCategoryVO vo : result) {
            List<Map> mapList = new ArrayList<>();
            //根据资源分类查询对应资源表
            List<PlatMetaTableEntity> tables = platMetaTableMapper.selectAllTable(vo.getId().toString());
            //拿到所有的资源表查询资源表里面的数据数量
            for (PlatMetaTableEntity platMetaTableEntity : tables) {
                List<ResourceSimpVO> cameraTypeOne = new ArrayList<>();
                List<ResourceSimpVO> cameraTypeThree = new ArrayList<>();
                List<ResourceCategoryVO> count = new ArrayList<>();
                Map<String, Object> dataCountMap = new HashMap<>();
                List<ResourceSimpVO> tableSimpInfo = new ArrayList<>();
                //根据资源表名称查询对应资源数量
                if (platMetaTableEntity.getName().equals("无人机")) {
                    tableSimpInfo = platMetaFieldMapper.findAllUav(districtCode);
                    platMetaTableEntity.setName("无人机");
                    vo.setFlag(1);

                } else if (platMetaTableEntity.getName().equals("视频监控")) {
                    tableSimpInfo = platMetaFieldMapper.findAllCamera1(new Page(1, Integer.MAX_VALUE), longitude,
                            latitude, districtCode, radius);
                    cameraTypeOne = tableSimpInfo.stream().filter(
                            resourceSimpVO -> resourceSimpVO.getMonitoringType().equals("1")).collect(
                            Collectors.toList());
                    cameraTypeThree = tableSimpInfo.stream().filter(
                            resourceSimpVO -> resourceSimpVO.getMonitoringType().equals("3")).collect(
                            Collectors.toList());
                    platMetaTableEntity.setName("视频监控");
                    vo.setFlag(1);
                } else {
                    tableSimpInfo = platMetaFieldMapper.findTableSimpInfo(
                            platMetaTableEntity.getPrefix() + platMetaTableEntity.getCode(), districtCode);
                    vo.setFlag(0);
                }
                String resourceIcon = platMetaFieldMapper.findResourceIcon(platMetaTableEntity.getName());
                vo.setImg(resourceIcon);
                //应产品要求地图图标和资源分类图标分开
                String iconImg = platMetaFieldMapper.findIconImg(platMetaTableEntity.getName());
                //判断是否在范围里面  如果不传参数，直接返回全部
                if (!StringUtils.isNotBlank(longitude) && !StringUtils.isNotBlank(latitude) && !StringUtils.isNotBlank(
                        radius)) {
                    dataCountMap.put("resourceCount", tableSimpInfo.size() + "");
                } else {
                    // 如果传参数   按照范围里面的数据数量返回
                    tableSimpInfo.forEach(resourceSimpVO -> {
                        if (StringUtils.isNotBlank(resourceSimpVO.getLongitude()) && StringUtils.isNotBlank(
                                resourceSimpVO.getLatitude())) {
                            double longitudeT = Double.parseDouble(resourceSimpVO.getLongitude());
                            double latitudeT = Double.parseDouble(resourceSimpVO.getLatitude());
                            //转数据
                            //查询经纬度范围
                            double distance = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude),
                                    Double.parseDouble(latitude),
                                    longitudeT, latitudeT);
                            if (distance <= Double.parseDouble(radius)) {
                                count.add(vo);
                            }
                        }
                    });

                    dataCountMap.put("resourceCount", "" + count.size());
                }
                dataCountMap.put("img", resourceIcon);
                dataCountMap.put("iconImg", iconImg);
                dataCountMap.put("resourceName", platMetaTableEntity.getName());
                if (platMetaTableEntity.getName().equals("视频监控")) {
                    List<Map> listmap = new ArrayList<>();
                    Map<String, String> objectObjectHashMap = new HashMap<>();
                    Map<String, String> objectObjectHashMap1 = new HashMap<>();
                    objectObjectHashMap.put("type", "1");
                    objectObjectHashMap.put("typeName", "防火监控");
                    objectObjectHashMap.put("cameraTypeSum", cameraTypeOne.size() + "");
                    //查询防火监控数量
                    objectObjectHashMap1.put("type", "3");
                    objectObjectHashMap1.put("typeName", "卡口监控");
                    objectObjectHashMap1.put("cameraTypeSum", cameraTypeThree.size() + "");
                    //查询卡口监控数量
                    listmap.add(objectObjectHashMap);
                    listmap.add(objectObjectHashMap1);
                    dataCountMap.put("resourceList", listmap);
                }
                dataCountMap.put("tableId", platMetaTableEntity.getId());
                dataCountMap.put("resourceLayerName", platMetaTableEntity.getCode());
                dataCountMap.put("tableName", platMetaTableEntity.getPrefix() + platMetaTableEntity.getCode());
                if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(
                        radius)) {
                    if (count.size() != 0) {
                        mapList.add(dataCountMap);
                        vo.setResourceList(mapList);
                    }
                } else {
                    mapList.add(dataCountMap);
                    vo.setResourceList(mapList);
                }
            }
        }
        //新加资源大类计算
        List<ResourceCategoryVO> collect = result.stream().filter(
                resourceCategoryVO -> CollectionUtil.isNotEmpty(resourceCategoryVO.getResourceList())).collect(
                Collectors.toList());
        for (ResourceCategoryVO vo : collect) {
            int categoryNum = 0;
            List<Map> resourceList = vo.getResourceList();
            for (Map map : resourceList) {
                if (StringUtils.isNotBlank(map.get("resourceCount").toString())) {
                    int resourceCount = Integer.parseInt(map.get("resourceCount").toString());
                    categoryNum = categoryNum + resourceCount;
                }
            }
            vo.setCategoryNum(categoryNum);
        }
        return collect;
        //return result ;
    }


    @Override
    public List<ResourceCategoryVO> findOtherResource(Long parentId, String longitude, String latitude, String radius) {
        //传值为4
        List<ResourceCategoryVO> result = fireResourceCategoryDao.selectListByParentId(parentId);
        for (ResourceCategoryVO vo : result) {
            //拿到数据查询
            String tableName = ResourceEnums.code2Str(vo.getResourceName());
            //根据tableName查询对应表里面数据


        }
        return null;
    }


    @Override
    public List<ResourceSimpVO> findTableSimpInfo(String tableName, String tableId, String longitude, String latitude,
                                                  String radius, String districtCode) {
        if (StringUtils.isNotBlank(districtCode)) {
            districtCode = districtCode + "%";
        }
        List<ResourceSimpVO> tableSimpInfo = new ArrayList<>();
        if (tableName.contains("uav")) {
            tableSimpInfo = platMetaFieldMapper.findAllUav(districtCode);
        } else if (tableName.contains("camera")) {
            tableSimpInfo = platMetaFieldMapper.findAllCamera1(new Page(1, Integer.MAX_VALUE), longitude, latitude,
                    districtCode, radius);
        } else {
            //根据tableName查询对应资源数据
            tableSimpInfo = platMetaFieldMapper.findTableSimpInfo(tableName, districtCode);
        }
        List<ResourceSimpVO> result = new ArrayList<>();
        if (!CollectionUtil.isEmpty(tableSimpInfo)) {
            tableSimpInfo.forEach(resourceSimpVO -> {
                if (tableName.contains("uav") || tableName.contains("camera") || tableName.contains("hlyhlycode")) {
                    resourceSimpVO.setFlag(1);
                } else {
                    resourceSimpVO.setFlag(0);
                }

                if (tableName.contains("camera")) {
                    String name = platMetaTableMapper.selectNameByTableId(tableId);
                    String iconImg = fireResourceCategoryDao.selectIconImgByName(name);
                    resourceSimpVO.setIconImg(iconImg);
                    result.add(resourceSimpVO);
                } else {
                    if (StringUtils.isNotBlank(resourceSimpVO.getLongitude()) && StringUtils.isNotBlank(
                            resourceSimpVO.getLatitude())) {
                        double longitudeT = Double.parseDouble(resourceSimpVO.getLongitude());
                        double latitudeT = Double.parseDouble(resourceSimpVO.getLatitude());
                        resourceSimpVO.setTableId(tableId);
                        //转数据
                        //查询经纬度范围
                        if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)
                                && StringUtils.isNotBlank(radius)) {
                            double distance = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude),
                                    Double.parseDouble(latitude),
                                    longitudeT, latitudeT);
                            if (distance <= Double.parseDouble(radius)) {
                                //查询图标
                                //根据tableid查询table表名称
                                String name = platMetaTableMapper.selectNameByTableId(tableId);
                                String iconImg = fireResourceCategoryDao.selectIconImgByName(name);
                                resourceSimpVO.setIconImg(iconImg);
                                result.add(resourceSimpVO);
                            }
                        } else {
                            String name = platMetaTableMapper.selectNameByTableId(tableId);
                            String iconImg = fireResourceCategoryDao.selectIconImgByName(name);
                            resourceSimpVO.setIconImg(iconImg);
                            result.add(resourceSimpVO);
                        }
                    }
                }
            });
        }

        return result;
    }


    //根据资源查询行政区划树
    @Override
    public List<TopFloorDownDistrictCodeVO> topFloorDownDistrictCodeChildrenList(Long parentId, String longitude,
                                                                                 String latitude, String radius,
                                                                                 String districtCode) {
        if (StringUtils.isNotBlank(districtCode)) {
            districtCode = districtCode + "%";
        }
        List<TopFloorDownDistrictCodeVO> result = new ArrayList<>();
        List<String> codeList = new ArrayList<>();
        //根据资源分类查询对应资源表
        List<PlatMetaTableEntity> tables = platMetaTableMapper.selectAllTable(null);
        //拿到所有的资源表查询资源表里面的数据数量
        for (PlatMetaTableEntity platMetaTableEntity : tables) {
            List<String> tableSimpInfoCode = new ArrayList<>();
            //根据资源表名称查询对应资源数量
            if (platMetaTableEntity.getName().equals("无人机")) {
                tableSimpInfoCode = platMetaFieldMapper.findAllUavDistrict(longitude, latitude, districtCode, radius);

            } else if (platMetaTableEntity.getName().equals("视频监控")) {
                tableSimpInfoCode = platMetaFieldMapper.findAllCameraDistrict(longitude, latitude, districtCode,
                        radius);
            } else {
                tableSimpInfoCode = platMetaFieldMapper.findTableSimpInfoDistrict(longitude, latitude,
                        platMetaTableEntity.getPrefix() + platMetaTableEntity.getCode(), districtCode, radius);
            }
            codeList.addAll(tableSimpInfoCode);
        }
        //过滤相同的数据
        if (districtCode.length() > 6) {
            codeList = codeList.stream().distinct().collect(Collectors.toList());
            for (String code : codeList) {
                TopFloorDownDistrictCodeVO topFloorDownDistrictCodeVO = new TopFloorDownDistrictCodeVO();
                String districtName = platMetaFieldMapper.findDistrictName(code, code.length());
                topFloorDownDistrictCodeVO.setDistrictCodeName(districtName);
                topFloorDownDistrictCodeVO.setDistrictCode(code);
                result.add(topFloorDownDistrictCodeVO);
            }
        }

        //拿到存在资源的行政区划
        return result;
    }


    @Override
    public Map<String, List<FireSituationVO>> getSimpleGeoSourceNearbyRadius(String longitude, String latitude,
                                                                             String radius, String flag,
                                                                             String districtCode,
                                                                             Integer page, Integer rows)
            throws Exception {
        Map<String, List<FireSituationVO>> resultMap = new HashMap<>();
        //查询对应表plat_meta_table表里为  防火资源数据
        List<PlatTableVO> platTableVOList = platMetaTableService.selectAllTable(flag);
        //将表的名称拿到
        String tableNames = platTableVOList.stream().map(PlatTableVO::getTableName).collect(
                Collectors.toList()).toString();
        String subTableName = tableNames.substring(1, tableNames.length() - 1);
        //拿到所有的内容数据
        List<Map> tableInfoMaps = platMetaTableService.selectTableInfoByTableName1(longitude, latitude, subTableName,
                districtCode, page, rows, radius);
        //拿到数据匹配经纬度 和半径
        for (PlatTableVO platTableVO : platTableVOList) {
            for (Map map : tableInfoMaps) {
                List<Map> mapList = (List<Map>) map.get(platTableVO.getTableName());
                //拿到表数据去对比数据
                if (!CollectionUtil.isEmpty(mapList)) {
                    List<FireSituationVO> mapInfoList = checkData(platTableVO.getIconImg(), mapList,
                            platTableVO.getName(), platTableVO.getId(), platTableVO.getCode(),
                            platTableVO.getTableName(), longitude, latitude, radius);
                    if (!CollectionUtil.isEmpty(mapInfoList)) {
                        resultMap.put(platTableVO.getCode(), mapInfoList);
                    }
                }
            }
        }
        return resultMap;
    }


    @Override
    public List<ResourceSimpVO> findTableSimpInfoU(String tableName, String tableId, String longitude, String latitude,
                                                   String radius, String districtCode, Integer page, Integer rows) {
        if (StringUtils.isNotBlank(districtCode)) {
            districtCode = districtCode + "%";
        }
        List<ResourceSimpVO> tableSimpInfo = new ArrayList<>();
        if (tableName.contains("uav")) {
            IPage page1 = new Page<>(page, rows);
            tableSimpInfo = platMetaFieldMapper.findAllUav1(page1, longitude, latitude, districtCode, radius);
        } else if (tableName.contains("camera")) {
            IPage page1 = new Page<>(page, rows);
            tableSimpInfo = platMetaFieldMapper.findAllCamera1(page1, longitude, latitude, districtCode, radius);
        } else {
            //根据tableName查询对应资源数据
            IPage page1 = new Page<>(page, rows);
            tableSimpInfo = platMetaFieldMapper.findTableSimpInfo1(page1, tableName, districtCode, longitude, latitude,
                    radius);
        }
        List<ResourceSimpVO> result = new ArrayList<>();
        if (!CollectionUtil.isEmpty(tableSimpInfo)) {
            tableSimpInfo.forEach(resourceSimpVO -> {
                if (tableName.contains("uav") || tableName.contains("camera") || tableName.contains("hlyhlycode")) {
                    resourceSimpVO.setFlag(1);
                } else {
                    resourceSimpVO.setFlag(0);
                }
                if (StringUtils.isNotBlank(resourceSimpVO.getLongitude()) && StringUtils.isNotBlank(
                        resourceSimpVO.getLatitude())) {
//                    double longitudeT = Double.parseDouble(resourceSimpVO.getLongitude());
//                    double latitudeT = Double.parseDouble(resourceSimpVO.getLatitude());
                    resourceSimpVO.setTableId(tableId);
                    //转数据
                    //查询经纬度范围
                    if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
//                        double distance = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude),
//                                Double.parseDouble(latitude),
//                                longitudeT, latitudeT);
//                        if (distance <= Double.parseDouble(radius)) {
                        //查询图标
                        //根据tableid查询table表名称
                        String name = platMetaTableMapper.selectNameByTableId(tableId);
                        String iconImg = fireResourceCategoryDao.selectIconImgByName(name);
                        resourceSimpVO.setIconImg(iconImg);
                        result.add(resourceSimpVO);
                        //   }
                    } else {
                        String name = platMetaTableMapper.selectNameByTableId(tableId);
                        String iconImg = fireResourceCategoryDao.selectIconImgByName(name);
                        resourceSimpVO.setIconImg(iconImg);
                        result.add(resourceSimpVO);
                    }
                }
            });
        }

        return result;
    }

    private List<FireSituationVO> checkData(String iconImg, List<Map> mapList, String name, String tableId,
                                            String tableName, String code, String longitude, String latitude,
                                            String radius) {
        List<FireSituationVO> fireSituationVOList = new ArrayList<>();
        for (Map map : mapList) {
            if (map.containsKey("longitude") && map.containsKey("latitude")) {
                FireSituationVO fireSituationVO = getFireSituationVO(iconImg, name, tableId, tableName, code, map);
                fireSituationVOList.add(fireSituationVO);
            }

        }
        //处理返回数据
        return fireSituationVOList;
    }


    private FireSituationVO getFireSituationVO(String iconImg, String name, String tableId, String tableName,
                                               String code, Map map) {
        FireSituationVO fireSituationVO = new FireSituationVO();
        if (Objects.nonNull(map.get("longitude"))) {
            fireSituationVO.setLongitude(map.get("longitude").toString());
        }
        if (Objects.nonNull(map.get("latitude"))) {
            fireSituationVO.setLatitude(map.get("latitude").toString());
        }
        if (Objects.nonNull(map.get("id"))) {
            fireSituationVO.setId(map.get("id").toString());
        }
        if (Objects.nonNull(map.get("flag"))) {
            fireSituationVO.setFlag(Integer.parseInt(map.get("flag").toString()));
        }
//        fireSituationVO.setLongitude(map.get("longitude").toString());
//        fireSituationVO.setLatitude(map.get("latitude").toString());
//        fireSituationVO.setId(map.get("id").toString());
//        fireSituationVO.setFlag(Integer.parseInt(map.get("flag").toString()));
        if (Objects.nonNull(map.get("isOnline"))) {
            fireSituationVO.setIsOnline(Integer.parseInt(map.get("isOnline").toString()));
        }
        fireSituationVO.setName(name);
        fireSituationVO.setIconImg(iconImg);
        fireSituationVO.setResourceLayerName(tableId);
        fireSituationVO.setTableName(tableName);
        fireSituationVO.setTableId(tableId);
        if (Objects.nonNull(map.get("name"))) {
            fireSituationVO.setOtherName(map.get("name").toString());
        }
        //根据tableId查询icon
        // disposeFeignClient.select
        return fireSituationVO;
    }

    /**
     * 查询资源列表（返回指定公共字段）
     *
     * @param qryResourceListRequest qryResourceRequest
     *
     * @return QryResourceModel
     */
    @Override
    public PageData<List<QryResourceModel>> qryResourceList(QryResourceListRequest qryResourceListRequest) {
        if (CollectionUtil.isEmpty(qryResourceListRequest.getTableIds())) {
            return PageData.<List<QryResourceModel>>builder()
                    .count(0)
                    .current(qryResourceListRequest.getCurrent())
                    .size(qryResourceListRequest.getSize())
                    .datas(new ArrayList<>())
                    .build();
        }

        List<String> tableIds = qryResourceListRequest.getTableIds();
        List<PlatMetaTableEntityDTO> platMetaTableEntityDTOS = platMetaTableMapper.selectTableByTableIds(tableIds);
        List<String> tableNames = new ArrayList<>();
        Map<String, String> name2Id = new HashMap<>();
        platMetaTableEntityDTOS.forEach(platMetaTableEntityDTO -> {
            tableNames.add(platMetaTableEntityDTO.getPrefix() + platMetaTableEntityDTO.getCode());
            name2Id.put(platMetaTableEntityDTO.getPrefix() + platMetaTableEntityDTO.getCode(),
                    platMetaTableEntityDTO.getTableId());
        });

        StringBuffer countSqlStringBuffer = new StringBuffer("select count(t.id) from ( ");
        tableNames.forEach(tableName -> {
            countSqlStringBuffer.append("select id from ")
                    .append(tableName)
                    .append(" ")
                    .append("where xzqhcode like '").append(qryResourceListRequest.getDistrictCode()).append(
                    "%'").append(" and delete_flag = '0' ");
            if (StrUtil.isNotEmpty(qryResourceListRequest.getResourceName())) {
                countSqlStringBuffer.append(" ")
                        .append(" and name like ").append("'%").append(qryResourceListRequest.getResourceName()).append(
                        "%'");
            }
            countSqlStringBuffer
                    .append(" ")
                    .append(" union all ");
        });
        String countSql = countSqlStringBuffer.substring(0, countSqlStringBuffer.length() - 10);
        countSql = countSql + ") t";
        long count = fireResourceCategoryDao.executeCount(countSql);
        if (count <= 0) {
            return PageData.<List<QryResourceModel>>builder()
                    .count(0)
                    .current(qryResourceListRequest.getCurrent())
                    .size(qryResourceListRequest.getSize())
                    .datas(new ArrayList<>())
                    .build();
        }

        Integer offset = (qryResourceListRequest.getCurrent() - 1) * qryResourceListRequest.getSize();
        StringBuffer selectSqlStringBuffer = new StringBuffer("");
        tableNames.forEach(tableName -> {
            selectSqlStringBuffer
                    .append("select id, name, xzqh as district_name, xzqhcode as district_code, longitude, latitude, ")
                    .append("'")
                    .append(tableName)
                    .append("' as table_code, ")
                    .append("'")
                    .append(name2Id.get(tableName))
                    .append("' as table_id ")
                    .append("from ")
                    .append(tableName)
                    .append(" ")
                    .append("where xzqhcode like '").append(qryResourceListRequest.getDistrictCode()).append(
                    "%'").append(" and delete_flag = '0' ");
            if (StrUtil.isNotEmpty(qryResourceListRequest.getResourceName())) {
                selectSqlStringBuffer.append(" ")
                        .append(" and name like ").append("'%").append(qryResourceListRequest.getResourceName()).append(
                        "%'");
            }
            selectSqlStringBuffer
                    .append(" ")
                    .append(" union all ");
        });
        String selectSql = selectSqlStringBuffer.substring(0, selectSqlStringBuffer.length() - 10);
        selectSql = selectSql + " limit " + qryResourceListRequest.getSize() + " offset " + offset;
        List<QryResourceModel> qryResourceModels = fireResourceCategoryDao.executeSelect(selectSql);

        return PageData.<List<QryResourceModel>>builder()
                .count((int) count)
                .current(qryResourceListRequest.getCurrent())
                .size(qryResourceListRequest.getSize())
                .datas(qryResourceModels)
                .build();
    }

    /**
     * 查询设备列表（返回指定公共字段）
     *
     * @param qryDeviceListRequest qryDeviceRequest
     *
     * @return QryDeviceModel
     */
    @Override
    public PageData<List<QryDeviceModel>> qryDeviceList(QryDeviceListRequest qryDeviceListRequest) {
        if (CollectionUtil.isEmpty(qryDeviceListRequest.getTableIds())) {
            return PageData.<List<QryDeviceModel>>builder()
                    .count(0)
                    .current(qryDeviceListRequest.getCurrent())
                    .size(qryDeviceListRequest.getSize())
                    .datas(new ArrayList<>())
                    .build();
        }

        List<String> tableIds = qryDeviceListRequest.getTableIds();
        List<PlatMetaTableEntityDTO> platMetaTableEntityDTOS = platMetaTableMapper.selectTableByTableIds(tableIds);
        List<String> tableNames = new ArrayList<>();
        Map<String, String> name2Id = new HashMap<>();

        //是否需要单独处理视频监控表
        boolean dealCamera = false;
        platMetaTableEntityDTOS.forEach(platMetaTableEntityDTO -> {
            tableNames.add(platMetaTableEntityDTO.getPrefix() + platMetaTableEntityDTO.getCode());
            name2Id.put(platMetaTableEntityDTO.getPrefix() + platMetaTableEntityDTO.getCode(),
                    platMetaTableEntityDTO.getTableId());
        });
        if (tableNames.contains(TABLE_NAME_SHIPINJIANKONG)) {
            dealCamera = true;
        }
        tableNames.remove(TABLE_NAME_SHIPINJIANKONG);

        //计算视频监控数量
        long cameraCount = 0L;
        if (dealCamera) {
            StringBuffer cameraCountSqlStringBuffer = new StringBuffer("select count(id) from ");
            cameraCountSqlStringBuffer.append(TABLE_NAME_SHIPINJIANKONG).append(" ")
                    .append("where district_code like '").append(qryDeviceListRequest.getDistrictCode()).append("%'")
                    .append(" and picture_type = 0 ");
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getResourceName())) {
                cameraCountSqlStringBuffer.append(" ")
                        .append(" and name like ").append("'%").append(qryDeviceListRequest.getResourceName()).append(
                        "%'");
            }
            //监控设备状态都是正常
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getDeviceStatus()) && !"1".equals(
                    qryDeviceListRequest.getDeviceStatus())) {
                cameraCountSqlStringBuffer.append(" ")
                        .append(" and id = -1");
            }
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getNetStatus())) {
                cameraCountSqlStringBuffer.append(" ")
                        .append(" and device_status = '").append(qryDeviceListRequest.getNetStatus()).append("'");
            }
            cameraCount = fireResourceCategoryDao.executeCount(cameraCountSqlStringBuffer.toString());
        }

        long count = 0L;
        if (CollectionUtil.isNotEmpty(tableNames)) {
            StringBuffer countSqlStringBuffer = new StringBuffer("select count(t.id) from ( ");
            tableNames.forEach(tableName -> {
                countSqlStringBuffer.append("select id from ")
                        .append(tableName)
                        .append(" ")
                        .append("where xzqhcode like '").append(qryDeviceListRequest.getDistrictCode()).append("%'")
                        .append(" and delete_flag = '0' ");
                if (StrUtil.isNotEmpty(qryDeviceListRequest.getResourceName())) {
                    countSqlStringBuffer.append(" ")
                            .append(" and name like ").append("'%")
                            .append(qryDeviceListRequest.getResourceName()).append("%'");
                }
                if (StrUtil.isNotEmpty(qryDeviceListRequest.getDeviceStatus())) {
                    countSqlStringBuffer.append(" ")
                            .append(" and device_status = '").append(qryDeviceListRequest.getDeviceStatus())
                            .append("'");
                }
                if (StrUtil.isNotEmpty(qryDeviceListRequest.getNetStatus())) {
                    countSqlStringBuffer.append(" ")
                            .append(" and net_status = '").append(qryDeviceListRequest.getNetStatus())
                            .append("'");
                }

                countSqlStringBuffer
                        .append(" ")
                        .append(" union all ");
            });
            String countSql = countSqlStringBuffer.substring(0, countSqlStringBuffer.length() - 10);
            countSql = countSql + ") t";
            count = fireResourceCategoryDao.executeCount(countSql);
        }
        //数量相加
        count = count + cameraCount;
        if (count <= 0) {
            return PageData.<List<QryDeviceModel>>builder()
                    .count(0)
                    .current(qryDeviceListRequest.getCurrent())
                    .size(qryDeviceListRequest.getSize())
                    .datas(new ArrayList<>())
                    .build();
        }

        Integer offset = (qryDeviceListRequest.getCurrent() - 1) * qryDeviceListRequest.getSize();
        StringBuffer selectSqlStringBuffer = new StringBuffer("");
        tableNames.forEach(tableName -> {
            selectSqlStringBuffer
                    .append("select id, name, xzqh as district_name, xzqhcode as district_code, longitude, latitude, device_status, net_status, dz as address, ")
                    .append("'")
                    .append(tableName)
                    .append("' as table_code, ")
                    .append("'")
                    .append(name2Id.get(tableName))
                    .append("' as table_id ")
                    .append("from ")
                    .append(tableName)
                    .append(" ")
                    .append("where xzqhcode like '").append(qryDeviceListRequest.getDistrictCode()).append("%'").append(
                    " and delete_flag = '0' ");
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getResourceName())) {
                selectSqlStringBuffer.append(" ")
                        .append(" and name like ").append("'%").append(qryDeviceListRequest.getResourceName()).append(
                        "%'");
            }
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getDeviceStatus())) {
                selectSqlStringBuffer.append(" ")
                        .append(" and device_status = '").append(qryDeviceListRequest.getDeviceStatus())
                        .append("'");
            }
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getNetStatus())) {
                selectSqlStringBuffer.append(" ")
                        .append(" and net_status = '").append(qryDeviceListRequest.getNetStatus())
                        .append("'");
            }

            selectSqlStringBuffer
                    .append(" ")
                    .append(" union all ");
        });

        //处理视频监控
        String selectSql;
        if (dealCamera) {
            selectSqlStringBuffer.append(
                    "select cast(id as VARCHAR), name, district_name, district_code, longitude, latitude, '1' as device_status, device_status as net_status, address, ")
                    .append("'")
                    .append(TABLE_NAME_SHIPINJIANKONG)
                    .append("' as table_code, ")
                    .append("'")
                    .append(name2Id.get(TABLE_NAME_SHIPINJIANKONG))
                    .append("' as table_id ")
                    .append("from ")
                    .append(TABLE_NAME_SHIPINJIANKONG)
                    .append(" ")
                    .append("where district_code like '").append(qryDeviceListRequest.getDistrictCode()).append("%'")
                    .append(" and picture_type = 0 ");
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getResourceName())) {
                selectSqlStringBuffer.append(" ")
                        .append(" and name like ").append("'%").append(qryDeviceListRequest.getResourceName()).append(
                        "%'");
            }
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getDeviceStatus()) && !"1".equals(
                    qryDeviceListRequest.getDeviceStatus())) {
                selectSqlStringBuffer.append(" ")
                        .append(" and id = -1");
            }
            if (StrUtil.isNotEmpty(qryDeviceListRequest.getNetStatus())) {
                selectSqlStringBuffer.append(" ")
                        .append(" and device_status = '").append(qryDeviceListRequest.getNetStatus()).append("'");
            }
            selectSql = selectSqlStringBuffer.toString();
        } else {
            selectSql = selectSqlStringBuffer.substring(0, selectSqlStringBuffer.length() - 10);
        }

        selectSql = selectSql + " limit " + qryDeviceListRequest.getSize() + " offset " + offset;
        List<QryDeviceModel> qryResourceModels = fireResourceCategoryDao.executeSelect2(selectSql);

        return PageData.<List<QryDeviceModel>>builder()
                .count((int) count)
                .current(qryDeviceListRequest.getCurrent())
                .size(qryDeviceListRequest.getSize())
                .datas(qryResourceModels)
                .build();
    }

    /**
     * 设施详情
     *
     * @param tableId tableId
     * @param id      id
     *
     * @return QryDeviceModel
     */
    @Override
    public QryDeviceModel qryDeviceDetail(String tableId, String id) {
        PlatMetaTableEntityDTO platMetaTableEntityDTO = platMetaTableMapper.selectTableByTableId(tableId);
        String tableName = platMetaTableEntityDTO.getPrefix() + platMetaTableEntityDTO.getCode();
        StringBuffer selectSqlStringBuffer = new StringBuffer("");
        if (TABLE_NAME_SHIPINJIANKONG.equals(tableName)) {//视频监控
            selectSqlStringBuffer
                    .append("select cast(id as VARCHAR), name, district_name, district_code, longitude, latitude, '' as device_status, device_status as net_status, ")
                    .append("'")
                    .append(TABLE_NAME_SHIPINJIANKONG)
                    .append("' as table_code, ")
                    .append("'")
                    .append(tableId)
                    .append("' as table_id ")
                    .append("from ")
                    .append(TABLE_NAME_SHIPINJIANKONG)
                    .append(" ")
                    .append("where id = '").append(id).append("'");
        } else {
            selectSqlStringBuffer
                    .append("select id, name, xzqh as district_name, xzqhcode as district_code, longitude, latitude, device_status, net_status, ")
                    .append("'")
                    .append(tableName)
                    .append("' as table_code, ")
                    .append("'")
                    .append(tableId)
                    .append("' as table_id ")
                    .append("from ")
                    .append(tableName)
                    .append(" ")
                    .append("where id = '").append(id).append("'");
        }
        return fireResourceCategoryDao.executeSelect3(selectSqlStringBuffer.toString());
    }

    /**
     * 资源详情
     *
     * @param tableId tableId
     * @param id      id
     *
     * @return QryResourceModel
     */
    @Override
    public QryResourceModel qryResourceDetail(String tableId, String id) {
        PlatMetaTableEntityDTO platMetaTableEntityDTO = platMetaTableMapper.selectTableByTableId(tableId);
        String tableName = platMetaTableEntityDTO.getPrefix() + platMetaTableEntityDTO.getCode();
        StringBuffer selectSqlStringBuffer = new StringBuffer("");
        selectSqlStringBuffer
                .append("select id, name, xzqh as district_name, xzqhcode as district_code, longitude, latitude, ")
                .append("'")
                .append(tableName)
                .append("' as table_code, ")
                .append("'")
                .append(tableId)
                .append("' as table_id ")
                .append("from ")
                .append(tableName)
                .append(" ")
                .append("where id = '").append(id).append("'");
        return fireResourceCategoryDao.executeSelect4(selectSqlStringBuffer.toString());
    }

}
